package cn.xyf.mzmy.common.idempotent.core.aop;

import cn.xyf.mzmy.common.enums.GlobalErrorCodeConstants;
import cn.xyf.mzmy.common.exception.ServiceException;
import cn.xyf.mzmy.common.idempotent.core.annotation.Idempotent;
import cn.xyf.mzmy.common.idempotent.core.keysolver.IdempotentKeyResolver;
import cn.xyf.mzmy.common.idempotent.core.redis.IdempotentRedisDAO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 幂等注解的切面，实现幂等操作
 */
@Aspect
@Slf4j
public class IdempotentAspect {


    /**
     * IdempotentKeyResolver 集合
     */
    private final Map<Class<? extends IdempotentKeyResolver>, IdempotentKeyResolver> keyResolvers;

    private final IdempotentRedisDAO idempotentRedisDAO;

    public IdempotentAspect(List<IdempotentKeyResolver> keyResolvers, IdempotentRedisDAO idempotentRedisDAO) {
        this.keyResolvers = keyResolvers.stream().collect(Collectors.toMap(IdempotentKeyResolver::getClass,Function.identity()));
        this.idempotentRedisDAO = idempotentRedisDAO;
    }

    @Around(value = "@annotation(idempotent)")
    public Object aroundPointCut(ProceedingJoinPoint joinPoint, Idempotent idempotent) throws Throwable {
        // 0. 获得 IdempotentKeyResolver, 解析 Key
        IdempotentKeyResolver keyResolver = keyResolvers.get(idempotent.keyResolver());
        Assert.notNull(keyResolver, "找不到对应的 IdempotentKeyResolver");
        String key = keyResolver.resolver(joinPoint, idempotent);

        // 1. 根据redis相应key是否过期进行幂等判断
        Boolean success = idempotentRedisDAO.setIfAbsent(key, idempotent.timeout(), idempotent.timeUnit());
        // 锁定失败，抛出异常
        if (!success) {
            log.info("[aroundPointCut][方法({}) 参数({}) 存在重复请求]", joinPoint.getSignature().toString(), joinPoint.getArgs());
            throw new ServiceException(GlobalErrorCodeConstants.REPEATED_REQUESTS.getCode(), idempotent.message());
        }

        // 2.执行逻辑
        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            // 3. 异常时，删除 Key
            if (idempotent.deleteKeyWhenException()) {
                idempotentRedisDAO.delete(key);
            }
            throw throwable;
        }

    }

}
